package com.alexsun.queryview

import android.content.ContentValues
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val dbHelper = StudentDatabaseHelper(this)
        val db = dbHelper.writableDatabase

        val insertButton = findViewById<Button>(R.id.insert_button)
        insertButton.setOnClickListener {
            val studentId = findViewById<EditText>(R.id.student_id_input).text.toString()
            val name = findViewById<EditText>(R.id.name_input).text.toString()
            val values = ContentValues().apply {
                put("StudentID", studentId)
                put("Name", name)
            }
            db.insert("m_student", null, values)
        }

        val queryButton = findViewById<Button>(R.id.query_button)
        queryButton.setOnClickListener {
            val cursor = db.query("m_student", null, null, null, null, null, null)
            val students = mutableListOf<Student>()
            while (cursor.moveToNext()) {
                val studentIdIndex = cursor.getColumnIndex("StudentID")
                val nameIndex = cursor.getColumnIndex("Name")
                if (studentIdIndex >= 0 && nameIndex >= 0) {
                    val studentId = cursor.getString(studentIdIndex)
                    val name = cursor.getString(nameIndex)
                    students.add(Student(studentId, name))
                }
            }
            val adapter = StudentAdapter(students)
            val recyclerView: RecyclerView = findViewById(R.id.students_list)
            recyclerView.layoutManager = LinearLayoutManager(this);
            recyclerView.adapter = adapter
            cursor.close()
            Toast.makeText(this@MainActivity, "查询到 ${students.size} 条记录", Toast.LENGTH_SHORT).show()
        }

        findViewById<Button>(R.id.delete_button).setOnClickListener {
            db.delete("m_student", null, null)
            val adapter = StudentAdapter(listOf())
            val recyclerView: RecyclerView = findViewById(R.id.students_list)
            recyclerView.layoutManager = LinearLayoutManager(this);
            recyclerView.adapter = adapter
            Toast.makeText(this@MainActivity, "删除成功", Toast.LENGTH_SHORT).show()
        }
    }
}
